#include "stdafx.h"
#include "EntityCard.h"
#include"Graphic.h"
#include"Map.h"
#include"RegisterManagement.h"
#include"TheRichMan.h"
EntityCard::EntityCard()
{
	entity_identifier = 0;
	color = RGB(150, 150, 150);
	nBlock = 0;
}


EntityCard::~EntityCard()
{
}

EntityCard & EntityCard::operator()(std::wstring card_name_id, Entity & user)
{
	this->card_name_id = card_name_id;
	this->entity_identifier = user.GetIdentifier();
	int id = TheRichMan::instance.GetPlayerIdAt(user);
	if (id != -1)this->color = TheRichMan::instance.GetPlayerDateAt(id).GetColor();
	return *this;
}

void EntityCard::Read(std::istream & in)
{
	__super::Read(in);
	SaveHelper::Read(in, entity_identifier);
	SaveHelper::Read(in, card_name_id);
	SaveHelper::Read(in, color);
	SaveHelper::Read(in, nBlock);
}

void EntityCard::Write(std::ostream & out)
{
	__super::Write(out);
	SaveHelper::Write(out, entity_identifier);
	SaveHelper::Write(out, card_name_id);
	SaveHelper::Write(out, color);
	SaveHelper::Write(out, nBlock);
}
auto condition = [](Entity&entity)->bool
{
	if (dynamic_cast<EntityCard*>(&entity))return true;
	return false;
};
void EntityCard::OnMet(Map & map, Entity & others, MapBlockPos pos)
{
	//if (&others == &entity)return;
	Entity * entity = &map.GetEntityWithIdentifier(entity_identifier);
	entity = entity->IsValid() ? entity : nullptr;
	EventResult result;
	if (entity)
		result = map.UseCard(card_name_id, *entity, others);
	else
		result = map.UseCard(card_name_id, others, others);
	if (result == et_cancel)return;
	map.KillEntity(*this);
	auto vec = map.GetEntity(pos, condition);
	for (int i = 0; i < vec.size(); i++)
	{
		((EntityCard*)vec[i])->nBlock = i;
	}
}

void EntityCard::OnDraw(Graphic & gfx)
{
	gfx.DrawRectangle(-nBlock * 5 + ENTITY_SIZE / 1.5, -nBlock * 5 + ENTITY_SIZE / 2, ENTITY_SIZE - ENTITY_SIZE / 1.5, ENTITY_SIZE - ENTITY_SIZE / 2, color);
}

bool EntityCard::SpawnCardToMap(Map & map, MapBlockPos pos, std::wstring card_id, Entity & user)
{
	Entity & ec = map.Spawn(typeid(EntityCard), pos);
	if (!ec.IsValid())return false;
	EntityCard & entity_card = (EntityCard&)ec;
	entity_card(card_id, user);
	auto vec = map.GetEntity(pos, condition);
	entity_card.nBlock = vec.size();
	return true;
}